import axios from "axios"
import { Message } from "element-ui"
import Cookies from 'js-cookie';

// import router from '@/router'

const Axios = axios.create({
  responseType: "json",
  withCredentials: true // 是否允许带cookie这些
})

/* //POST传参序列化(添加请求拦截器) */
Axios.interceptors.request.use(
  (config) => {
    // 若是有做鉴权token , 就给头部带上token
    let token = Cookies.get("token");
    if (token !== undefined) {
      config.headers.Authorization = "Bearer " + token;
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

/* //返回状态判断(添加响应拦截器) */
Axios.interceptors.response.use(
  (res) => {
    /* //对响应数据做些事 */
    if (res.status === 200) {
      return res.data ? res.data : {}
    } else {
      Message({
        message: res.data.msg,
        type: "error",
        duration: 5 * 1000
      })
      return Promise.reject(res.data)
    }
  },
  (error) => {
    let { message } = error
    if (message === "Network Error") {
      message = "后端接口连接异常"
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时"
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常"
    }
    Message({
      message: message,
      type: "error",
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default Axios
